
from starlette.responses import JSONResponse

from models.user import User
from schemas.users import UsersResponse, UserResponse, RoleResponse, PermissionResponse


# 格式化用户响应
def set_user_response(user: User) -> UserResponse | None:
    if user is None:
        return None
    return UserResponse(
        created_at=user.created_at,
        email=user.email,
        id=user.id,
        nickname=user.nickname,
        phone_number=user.phone_number,
        username=user.username,
        roles = [RoleResponse(
            created_at=role.created_at,
            description=role.description,
            id=role.id,
            name=role.name,
            permissions = [PermissionResponse(
                created_at=permission.created_at,
                description=permission.description,
                father_id=permission.father_id,
                id=permission.id,
                name=permission.name,
            ) for permission in role.permissions]
        ) for role in user.roles]
    )

class UserRepository:
    def __init__(self, db):
        self.db = db

    def create_or_update_user(self, user:User) -> User:
        self.db.add(user)
        self.db.commit()
        self.db.refresh(user)
        return set_user_response(user)

    def get_user_by_username(self, username:str) -> User:
        user = self.db.query(User).filter_by(username=username).first()
        return user

    def get_user_obj_by_id(self, user_id:int):
        user = self.db.query(User).filter_by(id=user_id).first()
        return user

    def get_user_by_email(self, email:str) -> User:
        user = self.db.query(User).filter_by(email=email).first()
        return user

    def get_user_by_phone_number(self, phone_number:str) -> User:
        user = self.db.query(User).filter_by(phone_number=phone_number).first()
        return user

    def get_user_by_id(self, user_id:int):
        user = self.db.query(User).filter_by(id=user_id).first()
        return set_user_response(user)

    def filter_user(self,page:int|None, size:int|None, username:str|None=None) -> UsersResponse:
        if username is not None:
            users = self.db.query(User).filter(User.username.like(f"%{username}%")).offset((page-1)*size).limit(size).all()
            total = self.db.query(User).filter(User.username.like(f"%{username}%")).count()
        else:
            users = self.db.query(User).offset((page-1)*size).limit(size).all()
            total = self.db.query(User).count()

        users = [user for user in users]

        return UsersResponse(data=[set_user_response(user) for user in users], paging={"page":page,"size":size,"total":total})

    def delete_user(self,user_id:int):
        user = self.db.query(User).filter_by(id=user_id).first()
        self.db.delete(user)
        self.db.commit()
        return JSONResponse(content={"message":"success"},status_code=200)
